package com.spillman.signtab.preferences;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import android.preference.PreferenceGroup;
import android.preference.SwitchPreference;

import com.spillman.signtab.R;
import com.spillman.signtab.utils.MyAdmin;

public class MainPreference extends PreferenceFragment implements OnPreferenceChangeListener {

	static final int RESULT_ENABLE = 1;
	Preference pref;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getPreferenceManager().setSharedPreferencesName(getString(R.string.app_name));
		addPreferencesFromResource(R.xml.preferences);
		initPreferences(getPreferenceScreen());
	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		String summary = null;

		if (preference instanceof SwitchPreference) {
			if (preference.getKey().equals(getString(R.string.pref_key_admin_enabled)) && (Boolean) newValue == true) {
				pref = preference;
				getDialog();
			} else {
				((DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE))
						.removeActiveAdmin(new ComponentName(getActivity(), MyAdmin.class));
			}
		} else {
			summary = newValue.toString();
		}

		if (summary != null) {
			preference.setSummary(summary);
		}

		return true;
	}

	private void getDialog() {
		Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
		intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, new ComponentName(getActivity(), MyAdmin.class));
		intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "This device require device admin for locking )");
		startActivityForResult(intent, RESULT_ENABLE);

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case RESULT_ENABLE:
			if (resultCode == Activity.RESULT_OK) {
			} else {
				((SwitchPreference)pref).setChecked(false);
				
			}
		}
	}

	private void initPreferences(PreferenceGroup preferenceGroup) {
		for (int i = 0; i < preferenceGroup.getPreferenceCount(); i++) {
			Preference preference = preferenceGroup.getPreference(i);
			if (preference instanceof PreferenceGroup) {
				initPreferences((PreferenceGroup) preference);
			}

			String summary = null;

			if (preference instanceof SwitchPreference) {
				summary = null;
			} else {
				summary = getPreferenceScreen().getSharedPreferences().getString(preference.getKey(), null);
			}

			if (summary != null) {
				preference.setSummary(summary);
			}

			preference.setOnPreferenceChangeListener(this);
		}
	}
}
